﻿using PSI.Helper;
using PSI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PSI.Services {
    public class OrgService : PSIBaseService {
        public List<Models.Org> GetAllOrg()
        {

            var result = new List<Models.Org>();

            var sql = "select org_id, org_name, parent_id, org_code, org_full_name from psi_org";

            Query(sql, reader => {
                var org = new Models.Org
                {
                    Id = reader.GetString(0),
                    Name = reader.GetString(1),
                    ParentId = reader.GetString(2),
                    OrgCode = reader.GetString(3),
                    FullName = reader.GetString(4)
                };

                result.Add(org);
            });

            return result;
        }

        public List<Models.Org> BuildOrgTree()
        {
            var data = GetAllOrg();

            var result = new List<Models.Org>();

            var d = from item in data
                    where string.IsNullOrEmpty(item.ParentId)
                    orderby item.OrgCode
                    select item;
            foreach (var item in d) {
                var node = new Models.Org
                {
                    Name = item.Name,
                    Id = item.Id,
                    OrgCode = item.OrgCode,
                    FullName = item.FullName
                };

                BuildOrgTreeInternal(node, data);

                result.Add(node);
            }

            return result;
        }

        private void BuildOrgTreeInternal(Models.Org node, List<Models.Org> data)
        {
            var d = from item in data
                    where item.ParentId == node.Id
                    orderby item.OrgCode
                    select item;

            foreach (var item in d) {
                var n = new Models.Org
                {
                    Id = item.Id,
                    Name = item.Name,
                    OrgCode = item.OrgCode,
                    FullName = item.FullName
                };

                node.Children.Add(n);

                BuildOrgTreeInternal(n, data); // 递归调用本身方法
            }
        }
    }
}